#include <stdio.h>
#include <time.h>
#include <stdarg.h>
#include "logger.h"

void init_logger(modbus_client_t* client){
    char log_filename[64];
    snprintf(log_filename,sizeof(log_filename),"modbus_link_%d.log",client->link_id);

    client->log_file = fopen(log_filename,"w");
    if(!client->log_file){
        perror("Failedf to open log file");
        client->log_file = stderr;
    }

    log_message(client,"Logger initialized for link %d", client->link_id);
}

void log_message(modbus_client_t* client, const char* format, ...){
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    char time_str[20];
    strftime(time_str,sizeof(time_str),"%Y-%m-%d %H:%M:%S", tm_info);

    //已知参数的格式化输出
    fprintf(client->log_file, "[%s] [Link %d] ", time_str, client->link_id);

    //变参函数的格式化输出
    va_list args;
    va_start(args, format);
    vfprintf(client->log_file, format, args);
    va_end(args);
    
    fprintf(client->log_file, "\n");
    fflush(client->log_file);       // 会不会有延迟，可优化，需避免在系统运行中调用
}

void close_logger(modbus_client_t* client){
    if(client->log_file && client->log_file != stderr){
        fclose(client->log_file);
    }
}